package com.xy_pro.xymanager.exception;


import com.xy_pro.xymanager.auth.dto.ResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(AuthenticationException.class)
    public ResultResponse<Object> handleAuthenticationException(AuthenticationException ex) {

        logger.error("======handleAuthenticationException {}", ex.getMessage());
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("message", ex.getMessage());
        errorResponse.put("status", String.valueOf(HttpStatus.UNAUTHORIZED.value()));
        errorResponse.put("timestamp", String.valueOf(System.currentTimeMillis()));

        return ResultResponse.forbidden(ex.getMessage());

//        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);
    }

    @ExceptionHandler(UserInfoInValidateException.class)
    public ResponseEntity<Map<String, String>> handleUsernameExistsException(UserInfoInValidateException e) {

//        logger
        logger.error("======handleUsernameExistsException {}", e.getMessage());
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("message", e.getMessage());
        errorResponse.put("status", String.valueOf(HttpStatus.CONFLICT.value()));
        errorResponse.put("timestamp", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity.status(HttpStatus.CONFLICT)
                .body(errorResponse);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<Map<String, String>> handleAccessDeniedException(AccessDeniedException ex) {

        logger.error("======handleAccessDeniedException: {}", ex.getMessage());
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("message", ex.getMessage());
        errorResponse.put("status", String.valueOf(HttpStatus.FORBIDDEN.value()));
        errorResponse.put("timestamp", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body(errorResponse);
    }
}
